package com.talking.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.talking.R;
import com.talking.bean.InvitationBean;
import com.talking.databinding.ItemInvitationBinding;
import com.talking.model.Http;
import com.talking.presenter.UserPresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class InvitationAdapter extends ArrayAdapter<InvitationBean> {
    private static final int layoutId = R.layout.item_chart_me;
    private final Activity context;
    public InvitationAdapter(Activity context, List<InvitationBean> objects){
        super(context,layoutId,objects);
        this.context=context;
    }
    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        InvitationBean bean = getItem(position);
        @SuppressLint("ViewHolder") @NonNull ItemInvitationBinding binding = ItemInvitationBinding.inflate(LayoutInflater.from(context));
        binding.itemInvitationAccount.setText(bean.friendAccount);
        binding.itemInvitationNickname.setText(bean.remark);
        UserPresenter.getUserByAccount(bean.friendAccount, null, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                context.runOnUiThread(() -> {
                    try {
                        JSONObject jo = new JSONObject(Objects.requireNonNull(response.body()).string());
                        Glide.with(context).load(Http.BASE_URL+jo.getString("iconUrl")).apply(Utils.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.itemInvitationIcon);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        return binding.getRoot();
    }
}